<template>
  <AppNavBar> 购物车 </AppNavBar>
  <div class="fill"></div>
  <CheckboxGroup v-model="checked" v-if="goodsList" checked-color="#42b983">
    <swipe-cell v-for="(cartGoods, i) in goodsList" :key="cartGoods.id">
      <Checkbox
        @click="changeChecked(cartGoods.checked)"
        v-model="cartGoods.checked"
        :name="i"
      ></Checkbox>
      <card
        :price="cartGoods.goods.price"
        :desc="cartGoods.goods.description"
        :title="cartGoods.goods.title"
        class="goods-card"
        :thumb="cartGoods.goods.cover_url"
      >
        <template #footer>
          <Stepper
            :max="cartGoods.goods.stock"
            @change="(newNum) => changeNum(newNum, cartGoods.id)"
            v-model="cartGoods.num"
          />
        </template>
      </card>
      <template #right>
        <Button
          square
          text="删除"
          type="danger"
          @click="deleteCartGoods(cartGoods.id)"
          class="delete-button"
        />
      </template>
    </swipe-cell>
    <div class="fillCell"></div>
  </CheckboxGroup>
  <submit-bar
    :price="totalMoney * 100"
    button-text="提交订单"
    @submit="onSubmit"
  >
    <checkbox
      v-model="allChecked"
      :name="goodsList.length"
      checked-color="#42b983"
      @click="changeAll"
      >全选</checkbox
    >
  </submit-bar>
</template>

<script>
import { ref, watch } from 'vue'
import AppNavBar from '@/components/library/AppNavBar.vue'
import { getAddresses } from '@/api/address'
import { getCart, changeCartNum, checkedCart, deleteCart } from '@/api/shopcart'
import { SwipeCell, Button, Card, Checkbox, CheckboxGroup, Stepper, SubmitBar, Dialog, Toast } from 'vant'
import { useRouter } from 'vue-router'
export default {
  name: 'ShopCart',
  components: { AppNavBar, SwipeCell, Button, Card, Checkbox, CheckboxGroup, Stepper, SubmitBar },
  setup () {
    const router = useRouter()
    const goodsList = ref([])
    const checked = ref([]) // 存储的是每个checkbox的下标
    const checkedStatic = []
    const allChecked = ref(false)
    // 记录选中的商品的id
    const ids = []
    const totalMoney = ref(0)
    watch(() => checked.value.length, () => {
      // 全选逻辑
      allChecked.value = goodsList.value.length === checked.value.length && checked.value.length !== 0
      // 总金额逻辑，根据checked值判断
      totalMoney.value = checked.value.length && checked.value.reduce((accumulator, currentValue) => {
        // 存在在checked中的就加
        return accumulator + goodsList.value[currentValue].goods.price
      }, 0)
    }, { immediate: true })
    const initCart = () => {
      getCart().then(res => {
        if (res.status === 200) {
          // 初始化绑定选中状态
          res.data.data.forEach((c, i) => {
            c.checked = c.is_checked === 1
            if (c.is_checked === 1) {
              checked.value.push(i)
            }
            checkedStatic.push(i)
          })
          goodsList.value = res.data.data
        }
      })
    }
    initCart()
    // 改变数量
    const changeNum = async (newNum, id) => {
      await changeCartNum(id, newNum)
    }
    // 提交购物车
    const onSubmit = async () => {
      // 首先查询是否有默认地址
      const res = await getAddresses()
      if (!res.data.data.find(a => a.is_default === 1)) {
        Toast.success('您还没有默认地址！请先添加默认地址')
        router.push('/address')
      } else {
        router.push('/preview')
      }
    }
    // 改变单个状态 直接将数组提交，进行改变即可
    const changeChecked = async () => {
      // 通过 checked 添加
      checked.value.forEach(i => {
        ids.push(goodsList.value[i].id)
      })
      await checkedCart({ cart_ids: ids })
    }
    // 改变所有状态 最大的作用在于展示页面
    const changeAll = () => {
      if (allChecked.value) {
        checked.value = checkedStatic
      } else {
        checked.value = []
      }
      // 手动调用改变状态
      changeChecked()
    }

    // 删除购物车商品
    const deleteCartGoods = (id) => {
      Dialog.confirm({
        title: '移除商品',
        message:
          '您确定要将该商品移出购物车吗？'
      })
        .then(async () => {
          deleteCart(id).then(res => {
            if (res.status === 204) {
              Toast.success('移除成功！')
              // 后台数据已经改变，不需要重新发送请求，可以直接删除本地，加快优化
              goodsList.value = goodsList.value.filter(goods => goods.id !== id)
            } else {
              Toast.fail('移除失败！')
            }
          })
        })
    }
    return {
      goodsList,
      checked,
      changeNum,
      onSubmit,
      allChecked,
      changeChecked,
      changeAll,
      totalMoney,
      deleteCartGoods
    }
  }
}
</script>

<style scoped lang='less'>
.fill {
  margin-top: 53px;
}
:deep(.van-button) {
  height: 100%;
}
.van-checkbox-group {
  .van-swipe-cell {
    :deep(.van-swipe-cell__wrapper) {
      display: flex;
      justify-content: center;
      align-items: center;
      .van-checkbox {
        padding-left: 5px;
        width: 30px;
      }
      .van-card {
        flex: 1;
      }
    }
  }
  .fillCell {
    height: 133px;
    width: 100%;
  }
}

.van-submit-bar {
  bottom: 70px;
}
</style>
